"""
添加测试数据脚本 - 为演示处理记录功能
"""
import sqlite3
import os
from datetime import datetime, timedelta
import random
import json

def add_test_processing_records():
    """添加测试处理记录"""
    db_path = "users.db"
    
    if not os.path.exists(db_path):
        print("数据库文件不存在")
        return
    
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    try:
        # 获取所有用户ID
        cursor.execute("SELECT id, username FROM users")
        users = cursor.fetchall()
        
        if not users:
            print("没有找到用户，无法添加测试数据")
            return
        
        print(f"找到 {len(users)} 个用户，开始添加测试数据...")
        
        # 定义一些测试操作类型和文件名
        operation_types = [
            "image_upload",
            "dicom_process", 
            "tdc_analysis",
            "vessel_extraction",
            "cbf_calculation",
            "cbv_calculation",
            "mtt_calculation",
            "ttp_calculation",
            "image_windowing",
            "data_export"
        ]
        
        test_files = [
            "brain_scan_001.dcm",
            "cardiac_study_002.dcm",
            "liver_perfusion_003.dcm",
            "renal_study_004.dcm",
            "stroke_assessment_005.dcm",
            "tumor_analysis_006.dcm"
        ]
        
        # 为每个用户添加一些随机的处理记录
        for user_id, username in users:
            num_records = random.randint(3, 8)  # 每个用户3-8条记录
            
            for i in range(num_records):
                # 随机选择操作类型和文件
                operation_type = random.choice(operation_types)
                file_name = random.choice(test_files) if random.random() > 0.3 else None
                
                # 生成随机时间（过去30天内）
                days_ago = random.randint(0, 30)
                hours_ago = random.randint(0, 23)
                minutes_ago = random.randint(0, 59)
                processing_time = datetime.utcnow() - timedelta(days=days_ago, hours=hours_ago, minutes=minutes_ago)
                
                # 生成操作详情
                operation_details = {
                    "version": "1.0",
                    "processing_method": random.choice(["normal", "maximum_slope"]),
                    "frame_range": {
                        "start": random.randint(1, 5),
                        "end": random.randint(20, 50)
                    },
                    "parameters": {
                        "enable_invert": random.choice([True, False]),
                        "color_map": random.choice(["jet", "hot", "cool"]),
                        "interpolation": random.choice([True, False])
                    }
                }
                
                # 随机处理时间（0.5秒到10秒）
                duration_ms = random.randint(500, 10000)
                
                # 大部分成功，少数失败
                status = random.choices(["success", "failed"], weights=[85, 15])[0]
                error_message = None
                
                if status == "failed":
                    error_messages = [
                        "内存不足",
                        "文件格式不支持", 
                        "网络连接超时",
                        "处理参数无效",
                        "磁盘空间不足"
                    ]
                    error_message = random.choice(error_messages)
                
                # 插入记录
                cursor.execute("""
                    INSERT INTO data_processing_records 
                    (user_id, operation_type, operation_details, file_name, processing_time, duration_ms, status, error_message)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                """, (
                    user_id,
                    operation_type,
                    json.dumps(operation_details, ensure_ascii=False),
                    file_name,
                    processing_time,
                    duration_ms,
                    status,
                    error_message
                ))
            
            print(f"为用户 {username} 添加了 {num_records} 条处理记录")
        
        conn.commit()
        
        # 显示统计信息
        cursor.execute("SELECT COUNT(*) FROM data_processing_records")
        total_records = cursor.fetchone()[0]
        
        cursor.execute("SELECT COUNT(*) FROM data_processing_records WHERE status = 'success'")
        success_records = cursor.fetchone()[0]
        
        cursor.execute("SELECT COUNT(*) FROM data_processing_records WHERE status = 'failed'")
        failed_records = cursor.fetchone()[0]
        
        print(f"\n✅ 测试数据添加完成！")
        print(f"📊 总记录数: {total_records}")
        print(f"✅ 成功记录: {success_records}")
        print(f"❌ 失败记录: {failed_records}")
        
        # 显示最近的几条记录
        cursor.execute("""
            SELECT u.username, dpr.operation_type, dpr.file_name, dpr.status, dpr.processing_time
            FROM data_processing_records dpr
            JOIN users u ON dpr.user_id = u.id
            ORDER BY dpr.processing_time DESC
            LIMIT 5
        """)
        recent_records = cursor.fetchall()
        
        print(f"\n🕒 最近的5条记录:")
        for username, op_type, filename, status, proc_time in recent_records:
            print(f"  {username} | {op_type} | {filename or 'N/A'} | {status} | {proc_time}")
        
    except Exception as e:
        print(f"添加测试数据失败: {e}")
        conn.rollback()
    finally:
        conn.close()

if __name__ == "__main__":
    add_test_processing_records() 